package com.jpz.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jpz.bean.User;
import com.jpz.service.Userservice;

@RequestMapping("/fileup")
@Controller
public class Fileupcontroller {
	@Autowired
	Userservice userservice;
	
	//开始上传的代码
	@RequestMapping("/goup")
	public String fileup(@RequestParam("file") MultipartFile file,Model model,HttpServletRequest request,Integer uid) {
		File path = createDir(request.getSession().getServletContext());
		String fileName=createName(file.getOriginalFilename());
		File f=new File(path, fileName);
		if (!file.isEmpty()) {
			try {
				file.transferTo(f);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//对路径的操作
		String absolutePath = f.getAbsolutePath();
		int indexOf = absolutePath.indexOf("Dida");
		String substring = absolutePath.substring(indexOf+5);
		String replaceAll = substring.replaceAll("\\\\", "/");
		//将路径存入数据库
		User user = userservice.selectById(uid);
		user.setPhoto(replaceAll);
		userservice.updateById(user);
		//存值到页面改变后  用于显示
		model.addAttribute("user", user);
		return "/photo.jsp";
	}
	
	
	// 创建目录---以日期，一天一个文件夹
		private File createDir(ServletContext context) {
			String realPath = context.getRealPath("/touxiang");
			String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
			File file = new File(realPath, date);
			if (!file.exists()) {
				file.mkdir();
			}
			return file;
		}

		// 创建文件名--区分同名文件,在文件名前加上当前的时间
		private String createName(String name) {
			return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime()) + "_" + name;
		}
	}


